package com.allenkerr.dao.impl;

import com.allenkerr.dao.ProductDao;
import com.allenkerr.pojo.Product;
import com.allenkerr.vo.ResultModel;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 小柯(Allen Kerr) on 17.5.2 9:24.
 */
@Repository
public class ProductDaoImpl implements ProductDao {

    @Autowired
    private SolrServer solrServer;

    @Override
    public ResultModel queryProducts(SolrQuery solrQuery) throws Exception {
        //执行查询并获取响应
        QueryResponse queryResponse = solrServer.query(solrQuery);

        //从响应中获取查询结果集
        SolrDocumentList docList = queryResponse.getResults();

        //创建resultModel对象
        ResultModel<Product> resultModel = new ResultModel();
        List<Product> productList = new ArrayList<>();

        //转换结果集
        if (docList != null) {
            //总记录数
            resultModel.setRecordCount(docList.getNumFound());
            //遍历结果集
            for (SolrDocument doc : docList) {
                Product product = new Product();
                // 商品编号
                product.setPid(String.valueOf(doc.get("id")));
                // 商品名称
                //=================================高亮=================================
                Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
                if (highlighting != null) {
                    List<String> list = highlighting.get(doc.get("id")).get("product_name");
                    if (list != null && list.size() > 0) {
                        product.setName(list.get(0));
                    } else {
                        product.setName(String.valueOf(doc.get("product_name")));//没有高亮内容
                    }
                } else {
                    product.setName(String.valueOf(doc.get("product_name")));//没有高亮内容
                }
                //=================================高亮=================================
                // 价格
                if (doc.get("product_price") != null && !"".equals(doc.get("product_price"))) {
                    product.setPrice(Float.parseFloat(String.valueOf(doc.get("product_price"))));
                }
                // 商品分类名称
                product.setCatalog_name(String.valueOf(doc.get("product_catalog_name")));
                // 图片名称
                product.setPicture(String.valueOf(doc.get("product_picture")));

                //添加到商品集合
                productList.add(product);
            }
            resultModel.setList(productList);
        }
        return resultModel;
    }
}
